package cn.openea.perpartner.common.rabbit.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Configuration
@EnableAsync
public class RabbitConfig implements EnvironmentAware {
    private Environment env;


    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
    }

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(env.getProperty("rabbitmq.basic.exchange"));
    }

    @Bean
    public Queue fixedReplyQueue() {
        return new Queue(Objects.requireNonNull(env.getProperty("rabbitmq.basic.queue")));
    }

    /**
     * 将队列和交换机绑定，并设置匹配键
     *
     * @return
     */
    @Bean
    public Binding fixedReplyQueueBinding() {
        return BindingBuilder
                .bind(fixedReplyQueue())
                .to(directExchange())
                .with(env.getProperty("rabbitmq.basic.routing_key"));
    }

    /**
     * 延时交换机
     * @return 延时交换机
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> arguments = new HashMap<>(1);
        arguments.put("x-delayed-type", "direct");
        return new CustomExchange(env.getProperty("rabbitmq.delay.exchange"), "x-delayed-message", true, false, arguments);
    }

    /**
     * 延时发送队列
     * @return 延时发送队列。
     */
    @Bean
    public Queue delayQueue() {
        return new Queue(env.getProperty("rabbitmq.delay.queue"), true, false, false);
    }

    /**
     * 延时绑定区
     * @return 延时绑定区
     */
    @Bean
    public Binding delayBind() {
        return BindingBuilder.bind(this.delayQueue()).to(this.delayExchange()).with(env.getProperty("rabbitmq.delay.routing_key")).noargs();
    }


    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }


}
